package com.ruoyi.channel.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.channel.domain.ChannelUserNumber;
import com.ruoyi.channel.domain.TChannelDataConf;
import com.ruoyi.channel.domain.bo.ChannelDisUser;
import com.ruoyi.channel.domain.bo.TChannelDataConfBo;
import com.ruoyi.channel.domain.bo.TChannelDataStaffBo;
import com.ruoyi.channel.domain.vo.TChannelDataConfVo;
import com.ruoyi.channel.mapper.TChannelDataConfMapper;
import com.ruoyi.channel.mapper.TChannelDataStaffMapper;
import com.ruoyi.channel.service.ITChannelDataConfService;
import com.ruoyi.channel.service.ITChannelDataStaffService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;

import java.util.Objects;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.util.CollectionUtils;

/**
 * 数据渠道管理Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-01
 */
@RequiredArgsConstructor
@Service
public class TChannelDataConfServiceImpl implements ITChannelDataConfService {

    private final TChannelDataConfMapper baseMapper;

    private final ITChannelDataStaffService channelDataStaffService;

    private final TChannelDataStaffMapper dataStaffMapper;

    /**
     * 查询数据渠道管理
     */
    @Override
    public TChannelDataConfVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询数据渠道管理列表
     */
    @Override
    public TableDataInfo<TChannelDataConfVo> queryPageList(TChannelDataConfBo bo, PageQuery pageQuery) {
        QueryWrapper<TChannelDataConf> lqw = buildQueryWrapper(bo);
        Page<TChannelDataConfVo> result = baseMapper.selectPageChannelDataList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询数据渠道管理列表
     */
    @Override
    public List<TChannelDataConfVo> queryList(TChannelDataConfBo bo) {
        QueryWrapper<TChannelDataConf> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private QueryWrapper<TChannelDataConf> buildQueryWrapper(TChannelDataConfBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<TChannelDataConf> lqw = Wrappers.query();
        lqw.like(bo.getChannelName() != null, "a.channel_name", bo.getChannelName());
        lqw.eq(StringUtils.isNotBlank(bo.getChannelDescribe()), "a.channel_describe", bo.getChannelDescribe());
        return lqw;
    }

    /**
     * 新增数据渠道管理
     */
    @Override
    @Transactional
    public Boolean insertByBo(TChannelDataConfBo bo) {
        TChannelDataConf add = BeanUtil.toBean(bo, TChannelDataConf.class);
        if (CollectionUtils.isEmpty(bo.getYwList())) {
            throw new ServiceException("业务员没有配置");
        }
        if (CollectionUtils.isEmpty(bo.getGlList())) {
            throw new ServiceException("管理员没有配置");
        }
        validEntityBeforeSave(add, "1");
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            dataConfig(add.getId(), bo);
            disUserInfoUpdate(add.getId(), "1");
        }
        return flag;
    }

    private void dataConfig(Long channelDateId, TChannelDataConfBo bo) {
        channelDataStaffService.saveStaffInfo(channelDateId, "1", bo.getGlList().stream().map(it -> {
            TChannelDataStaffBo tChannelDataStaffBo = new TChannelDataStaffBo();
            tChannelDataStaffBo.setUserId(it);
            return tChannelDataStaffBo;
        }).collect(Collectors.toList()));
        channelDataStaffService.saveStaffInfo(channelDateId, "2", bo.getYwList());
    }


    public void disUserInfoUpdate(Long channelDateId, String type) {
        ChannelDisUser channelDisUser = new ChannelDisUser();
        channelDisUser.setChannelDataId(channelDateId);
        channelDisUser.setType(type);
        //SpringUtils.context().publishEvent(channelDisUser);
        this.updateNewDisUserId(channelDisUser);
    }


    // 异步更新最新的人
//    @Async
//    @EventListener
    public void updateNewDisUserId(ChannelDisUser channelDisUser) {
        TChannelDataConf dataConf = new TChannelDataConf();
        // 查询当前分配的用户信息
        TChannelDataConfVo tChannelDataConfVo = baseMapper.selectVoById(channelDisUser.getChannelDataId());
        if (tChannelDataConfVo == null) {
            return;
        }
        String channelSource = tChannelDataConfVo.getChannelSource();
        // 第一次为null
        Long disUserId = tChannelDataConfVo.getDisUserId();
        // 查询一下可分配的人还有谁 如果只有一个人就还继续分配当前这个人 (根据用户ID排序)
        List<ChannelUserNumber> channelUserList = dataStaffMapper.getChannelUser(channelDisUser.getChannelDataId(), channelSource);
        if (CollectionUtils.isEmpty(channelUserList)) {
            dataConf.setDisUserId(-1L);
            dataConf.setId(tChannelDataConfVo.getId());
            baseMapper.updateById(dataConf);
            return;
        }
        List<Long> collect = channelUserList.stream().map(ChannelUserNumber::getUserId).distinct().sorted().collect(Collectors.toList());
        // 已分配过 查找下一个人
//        if (disUserId != -1) {
//
//            if (collect.size() == 1 && collect.contains(disUserId)) {
//                disUserId = null;
//            }
//        }
        //ChannelUserNumber channelNextUser = dataStaffMapper.getChannelNextUser(channelDisUser.getChannelDataId(), disUserId, channelSource);
        //if (channelNextUser == null) {
        //    dataConf.setDisUserId(-1L);
        //} else {
        //    dataConf.setDisUserId(channelNextUser.getUserId());
        //
        dataConf.setDisUserId(returnNextUser(disUserId, collect, channelDisUser.getType()));
        dataConf.setId(tChannelDataConfVo.getId());
        baseMapper.updateById(dataConf);
    }

    private Long returnNextUser(Long userId, List<Long> userList, String type) {
        for (Long userIdnNext : userList) {
            if (Objects.equals("2", type) ? (userIdnNext >= userId) : (userIdnNext > userId)) {
                return userIdnNext;
            }
        }
        return userList.get(0);
    }

    /**
     * 修改数据渠道管理
     */
    @Override
    @Transactional
    public Boolean updateByBo(TChannelDataConfBo bo) {
        TChannelDataConf update = BeanUtil.toBean(bo, TChannelDataConf.class);
        validEntityBeforeSave(update, "2");
        dataConfig(update.getId(), bo);
        int i = baseMapper.updateById(update);
        disUserInfoUpdate(bo.getId(), "2");
        return i > 0;
    }

    @Override
    public Boolean updateOpenByBo(TChannelDataConfBo bo) {
        TChannelDataConf dataConf = new TChannelDataConf();
        dataConf.setId(bo.getId());
        dataConf.setIsOpen(bo.getIsOpen());
        // 如果是开启  检测一下是否配置好了人员信息
        if (Objects.equals(bo.getIsOpen(), "1")) {
            int admin = baseMapper.checkDataConfig(bo.getId(), "1");
            int staff = baseMapper.checkDataConfig(bo.getId(), "2");
            if (!(admin > 0 && staff > 0)) {
                throw new ServiceException("没有配置人员信息不可开启");
            }
        }
        return baseMapper.updateById(dataConf) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TChannelDataConf entity, String type) {
        //TODO 做一些数据校验,如唯一约束
        LambdaQueryWrapper<TChannelDataConf> dataConfWrapper = new LambdaQueryWrapper<>();
        dataConfWrapper.eq(TChannelDataConf::getChannelSource, entity.getChannelSource());
        dataConfWrapper.ne(Objects.equals("2", type), TChannelDataConf::getId, entity.getId());
        Long count = baseMapper.selectCount(dataConfWrapper);
        if (count > 0) {
            throw new ServiceException("渠道标识不能重复");
        }
        dataConfWrapper.clear();
        dataConfWrapper.eq(TChannelDataConf::getChannelName, entity.getChannelName());
        dataConfWrapper.ne(Objects.equals("2", type), TChannelDataConf::getId, entity.getId());
        Long nameCount = baseMapper.selectCount(dataConfWrapper);
        if (nameCount > 0) {
            throw new ServiceException("渠道名称不能重复");
        }
    }

    /**
     * 批量删除数据渠道管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
